﻿using System;
using System.Web;
using System.Web.Security;
using Models;

namespace BLL
{
    public class AuthenticationService
    {

        private UserService _userService;

        public AuthenticationService()
        {
            _userService = new UserService();
        }

        public void SignIn(UserInfo user, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                user.UserName ,
                now,
                now.AddHours(24*365),
                createPersistentCookie,
                user.UserName,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public virtual void SignOut()
        {
            FormsAuthentication.SignOut();
        }


        public UserInfo GetAuthenticatedCustomer()
        {
       
            if (HttpContext.Current== null ||
                HttpContext.Current.Request == null ||
                !HttpContext.Current.Request.IsAuthenticated ||
                !(HttpContext.Current.User.Identity is FormsIdentity))
            {
                return null;
            }

            var formsIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
            var customer = GetAuthenticatedCustomerFromTicket(formsIdentity.Ticket);
            if (customer != null && customer.Active && !customer.Deleted && customer.IsRegistered())
            {
                return customer;
            }
            return null;
        }

        public virtual UserInfo GetAuthenticatedCustomerFromTicket(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
                throw new ArgumentNullException("ticket");

            var usernameOrEmail = ticket.UserData;

            if (String.IsNullOrEmpty(usernameOrEmail))
                return null;
            var customer = _userService.GetCustomerByUsername(usernameOrEmail);
            return customer;
        }
    }
}